# -*- coding: utf-8 -*-

import json

from django.utils.decorators import method_decorator
from django.utils.encoding import smart_unicode
from django.views.decorators.http import require_POST
from django.views.generic import TemplateView

from common.admin import db as user_db
from common.level_strategy import db as level_db
from common.utils import track_logging
from common.utils.api import token_required
from common.utils.decorator import response_wrapper, safe_wrapper
from common.utils.tz import utc_to_local_str

_LOGGER = track_logging.getLogger(__name__)


class UserLevelStrategyView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        cond = user_db.get_mchids_filter_by_user(req.user_id)
        if cond and not query_dct.get('mch_id', ''):
            query_dct['mch_id'] = cond
        _LOGGER.info('MchUserView get mchs: %s, ', query_dct)

        items, total_count = level_db.list_user_level_strategy(query_dct)

        resp_items = []
        for item in items:
            data = item.as_dict()
            data['created_at'] = utc_to_local_str(data['created_at'])
            data['updated_at'] = utc_to_local_str(data['updated_at'])
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    def post(self, req):
        param_dct = json.loads(req.body)
        level_db.upsert_user_level_strategy(param_dct)
        return {}

    def put(self, req):
        return self.post(req)

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(UserLevelStrategyView, self).dispatch(*args, **kwargs)


class SingleUserLevelStrategyView(TemplateView):
    def get(self, req, id):
        mch_user = level_db.get_user_level_strategy(id=int(id))
        data = mch_user.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        return data

    def post(self, req, id):
        return self.put(req, id)

    def put(self, req, id):
        query_dct = json.loads(smart_unicode(req.body))
        if 'row' in query_dct:
            level_db.upsert_user_level(query_dct['row'], int(query_dct['row']['id']))
            level_db.upsert_user_level_strategy({}, int(id)) # Updates user_level_strategy->updated_at only
        else:
            level_db.upsert_user_level_strategy(query_dct['data'], int(id))
        return {}

    def patch(self, req, id):
        query_dct = json.loads(smart_unicode(req.body))
        level_db.upsert_user_level_strategy(query_dct, int(id))
        return {}

    def delete(self, req, id):
        level_db.delete_user_level_strategy(int(id))
        _LOGGER.info('delete channel: %s, user: %s', id, req.user_id)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleUserLevelStrategyView, self).dispatch(*args, **kwargs)


@require_POST
@response_wrapper
@token_required
@safe_wrapper
def UserLevelStrategyCreate(req):
    _LOGGER.info('UserLevelStrategyCreate : %s', req.body)
    query_dct = json.loads(smart_unicode(req.body))
    strategy = level_db.upsert_user_level_strategy(query_dct['strategy'])
    for item in query_dct['levels']:
        item['strategy_id'] = strategy.id
        level_db.upsert_user_level(item)
    return {}
